package org.anarcoding.twitterbot.providers;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Properties;

import org.anarcoding.twitterbot.model.AnarcoTwitterBotConf;
import org.anarcoding.twitterbot.model.AnarcoTwitterException;
import org.anarcoding.twitterbot.services.IAnarcoTwitterServicesImpl;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.eclipse.swt.SWT;

import com.anarcoding.util.SWTUtil;

public class AnarcoTwitterModelProvider {

	private static final String					IBATIS_CONFIGURACION	= "org/anarcoding/twitterbot/db/configuracion_db.xml";
	private static final String					DRIVER_DB				= "org.sqlite.JDBC";
	private static final String					URL_DB					= "jdbc:sqlite:" + "." + File.separator + "anarco_twitter_db.sqlite";
	private static final String					NS						= IAnarcoTwitterServicesImpl.class.getName();
	private static final String					SELECT_LISTA_DE_CONF	= NS + ".selectListaDeAnarcoTwitterBotConf";

	private static List< AnarcoTwitterBotConf >	botConfList;

	public static final SqlSessionFactory		sqlSessionFactory;

	static {
		Reader reader;
		SqlSessionFactory sessionFactory = null;

		try {
			reader = Resources.getResourceAsReader( IBATIS_CONFIGURACION );
			Properties datosDeConexion = new Properties();

			datosDeConexion.setProperty( "driver", DRIVER_DB );
			datosDeConexion.setProperty( "url", URL_DB );

			sessionFactory = new SqlSessionFactoryBuilder().build( reader, datosDeConexion );

		} catch( IOException e ) {
			SWTUtil.openDialog( null, "Error", "No existe el fichero de configuracion.", SWT.ICON_ERROR );
			e.printStackTrace();
		} finally {
			sqlSessionFactory = sessionFactory;
		}

	}

	public static List< AnarcoTwitterBotConf > getListaDeConfiguraciones() throws AnarcoTwitterException {
		if( botConfList != null )
			return botConfList;

		SqlSession session = sqlSessionFactory.openSession( false );

		botConfList = session.selectList( SELECT_LISTA_DE_CONF );

		return botConfList;
	}

}
